#include "iap.h"

u8  iap_write_flash(const u32 addr, const u8 *data, u32 len)
{
	u8 ret = TRUE, oft;
	u32 wraddr, cnt, nr, wrdata;
	
	__disable_irq();
	// must be 4byte
	cnt = len/4;
	
	wraddr = addr;
	for(nr=0; nr<cnt; nr++){
		wrdata = 0;
		wrdata += data[nr*4+0];
		wrdata += data[nr*4+1]<<8;
		wrdata += data[nr*4+2]<<16;
		wrdata += data[nr*4+3]<<24;
		ret = mml_sflc_write(wraddr, (unsigned char *)&wrdata, 4);	
		wraddr += 4;
		if(ret){
			 __enable_irq();
			return FALSE;
		}
	}

	if(len%4){
		oft = len%4;
		wrdata = 0x00000000;
		for(cnt=0; cnt<oft; cnt++){
			wrdata +=  (u32)(data[nr*4+cnt]<<(cnt*8));
		}

		for(cnt=oft; cnt<4; cnt++){
			wrdata +=  (u32)(0xFF<<(cnt*8));
		}
		
		ret = mml_sflc_write(wraddr, (unsigned char *)&wrdata, 4);
		if(ret){
			 __enable_irq();
			return FALSE;
		}
	}
	
	 __enable_irq();
 
	return ret;	
}


u8 iap_enter_upgrade(void)
{
	SYSP_ST * para;

	para= sys_para_get();
	if(!para){
		iap_debug("[IAP] get syspara error!\n");
		return 1;
	}	

	para->upgrade = TRUE;
	sys_para_set(*para);
	
	//mml_reset_system();
	iap_debug("[IAP] iap enter upgrade ...\n");
	
	return 0;
}




